package com.syuchen.protocol.http;

import java.util.HashMap;
import java.util.Map;

public class HttpResponseEncoder {

    public static Response encode(String jsonBody) {
        Response response = new Response();
        buildFirstLine(response, Response.OK);
        buildResponseBody(response, Response.Json_Content_Type, jsonBody);
        return response;
    }

    public static Response buildResponse(int status_code, String... params) {
        String contentType = "";
        String body = "";
        if (params.length == 2) {
            contentType = params[0];
            body = params[1];
        }
        Response response = new Response();
        buildFirstLine(response, status_code);
        buildResponseBody(response, contentType, body);
        return response;
    }

    /**
     * 初始化响应头的第一行
     */
    private static void buildFirstLine(Response response, int status_code) {
        response.setVersion(Response.HTTP1_1);
        response.setStatus_code(status_code);
        response.setStatus_description(Response.statusDescriptionMap.get(status_code));
    }

    /**
     * 初始化响应体以及相关的两个响应头字段
     */
    private static void buildResponseBody(Response response, String contentType, String body) {
        if (body != null && body.length() > 0) {
            Map<String, String> headers = new HashMap<>();
            headers.put(Response.Content_Type, contentType);
            headers.put(Response.Content_Length, String.valueOf(body.length()));
            response.setHeaders(headers);
            response.setBody(body);
        }
    }
}
